define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_history = (SamCtx) ->

		# --- Global Variables and Function ---------------

			$select = 
				"non-member":
					amount : ""
					type2 : ".all"
					text : "$14 and less"
				"low-income":
					amount : "$15.00"
					type2 : ".all"
					text : "$15 - $24"
				"personal":
					amount : "$25.00"
					type2 : ".all"
					text : "$25 - $39"
				"family":
					amount : "$45.00"
					type2 : ".family"
					text : "$40 and up"
			_dID = ""
			$this = $(ins = @)
			S = SamCtx
			$tpl = $('<tr>').html '
					<td><%= num+1 %></td>
					<td><%= donation_date%></td>
					<td>$<%= donation_amount %></td>'
			$selTPL = $('<div>').html '<input name="<%=  %>" />'

		# --- Core code of plugin -------------------------

			unless @mb_plugin()
				@mb_plugin 'history'

				# Initialization, adds table
				$this.find('.content').append("
					<table class='records'>
						<tbody>
							<tr>
								<th> Record </th>
								<th> Date </th>
								<th> Amount </th>
							</tr>
						</tbody>
					</table>")

				for i of $select
					$(".ind.add").append $('<option>').val(i).html($select[i].text)

				$.subscribe "mb.query", (e, arg) ->
					_type = arg['search_type']
					$this.find(".add.#{_type}").show()
					$this.find(".add:not(.#{_type})").hide()

				# Main subscription to obtain a donor_id
				$.subscribe "mb.donor", (e, arg) ->
					_dID = arg['donor_id']

					# Remove all non-header table rows (cleans the table)
					$this.find('.content tr:not(:has(th))').remove()

					# Query for all donation records using the donor_id
					$.couch.db("vcn-members").view 'app/donations', {key: _dID, success: (data) -> 

						# Create an empty array, then copy all of value object into this array
						# This is done so sorting can be accomplished
						recordlist = []
						recordlist[i] = data.rows[i].value for i of data.rows

						# Sort the array by donation date starting from most recent
						# Loop through this array and display the table of donations
						for i of recordlist.sort(H.sortby("donation_date", true))
							x = recordlist[i]
							content = S.content $tpl,
									num: Number(i)
									donation_date: x.donation_date
									donation_amount: x.donation_amount
							$this.find('.content tbody').append $('<tr>')
								.attr('id', x._id)
								.attr('index', Number(i)+1)
								.append content

						# This is kind of messy, I can't seem to get the width of a hidden table so I have
						# to clone it and hide it somewhere out of sight in order to calculate the dimensions and then
						# delete it afterwards.
						$('body').append $this.find('table.records').clone().attr('id', 'hidden').show()
							.css("position" 	: "absolute",
								"top"		: "-1000px" )
						$this.find('.content').css('width', "#{$('#hidden').width()+40}px")
						$('#hidden').remove()
						}

					return # return for the subscription


			# --- Button Event Handlers ------------------

				$this.find('[name="add_donation"]').on 'click', ->
					if $this.find('select.add').is(":hidden")
						amount = type2 = ""
						type = ".org"
					else
						type = ".ind"
						amount = $select[$('select.add', ins).val()].amount
						type2 = $select[$('select.add', ins).val()].type2

					$.publish "mb.add_donation", {donor_id : _dID, amount: amount, class1: type, class2: type2}
					S.app.setLocation "#/add_donation"
					return false

				# When a table row is clicked on, change background color to gray 
				# to mimic the "select" of options in an HTML selector, also modify the
				# selected row to have a classname of "selected"
				$this.find('.content table').on "mousedown", 'tr:not(:has(th))', ->
					$.publish "mb.donation", {id: $(@).attr('id')}
					S.app.setLocation "#/donation_detail"
					return

		return @
	return
